package com.coder.rental.utils;

import com.coder.rental.entity.Dept;
import org.springframework.beans.BeanUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author XueWenJie
 * @Date 2025/2/12
 * @Project auto_rental
 *
 * 用来查询部门树结构
 */
public class DeptTreeUtils {
    public static List<Dept> buildTree(List<Dept> deptList, int pid) {
        List<Dept> deptTree = new ArrayList<>();
        Optional.ofNullable(deptList).orElse(new ArrayList<>())
                .stream().filter(dept -> dept != null && dept.getPid() == pid)
                .forEach(dept -> {
                    Dept dept1 = new Dept();
                    BeanUtils.copyProperties(dept, dept1);
                    dept1.setChildren(buildTree(deptList, dept.getId()));
                    deptTree.add(dept1);
                });
        return deptTree;
    }
    /**
     * 自动构建完整的部门树，无论查询的是哪些部门
     * @param deptList 部门列表
     * @return 完整的部门树结构
     */
    public static List<Dept> buildTreeAuto(List<Dept> deptList) {
        if (deptList == null || deptList.isEmpty()) {
            return new ArrayList<>();
        }

        // 将列表转换为Map，以id为键，方便查找
        Map<Integer, Dept> deptMap = deptList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(Dept::getId, dept -> dept, (existing, replacement) -> existing));

        // 找出所有顶级节点（pid不在deptList中的节点）
        List<Dept> rootDepts = new ArrayList<>();
        Set<Integer> deptIds = deptMap.keySet();

        for (Dept dept : deptList) {
            if (dept != null) {
                // 如果父节点不在列表中，或者父节点是-1（虚拟根节点），则为根节点
                if (!deptIds.contains(dept.getPid()) || dept.getPid() == -1) {
                    rootDepts.add(dept);
                }
            }
        }

        // 递归设置子节点
        for (Dept dept : rootDepts) {
            setChildren(dept, deptMap);
        }

        return rootDepts;
    }

    /**
     * 递归设置子节点
     * @param parent 父节点
     * @param deptMap 部门映射
     */
    private static void setChildren(Dept parent, Map<Integer, Dept> deptMap) {
        List<Dept> children = new ArrayList<>();
        for (Dept dept : deptMap.values()) {
            if (dept != null && Objects.equals(dept.getPid(), parent.getId())) {
                children.add(dept);
                setChildren(dept, deptMap); // 递归设置子节点的子节点
            }
        }
        parent.setChildren(children);
    }
}
